package com.xtt._02_guava;

import com.google.common.base.Objects;
import com.google.common.collect.ComparisonChain;
import org.junit.Test;


/**
 * @Author xtt.
 * @Description: 使用guava提供Object扩展方法优雅实现equal compare toString 等实现
 * @Date:Create in 2017/9/19 0019 下午 22:37
 * @Modify By:
 */
public class ObjectTest {

    @Test
    public void test() {
        Person p1 = new Person("zs",23,"男");
        Person p2 = new Person("zs",23,"男");
        Person p3 = new Person("zs",24,"男");
        System.out.println(p1.equals(p2));//true
        System.out.println(p1.compareTo(p3));//-1
    }
}

class Person implements Comparable<Person>{

    public Person(String name, Integer age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    private Integer id;

    private String name;

    private Integer age;

    private String sex;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public int compareTo(Person o) {//使用guava写compareTo
        return ComparisonChain.start()
                .compare(age,o.age)
                .compare(sex,o.sex)
                .compare(name,o.name)
                .result();
    }
    @Override
    public boolean equals(Object o) { //guava 重写equals
        if(o instanceof Person) {
            Person p = (Person)o;
            return Objects.equal(name,p.name)
                    && Objects.equal(age,p.age)
                    && Objects.equal(sex,p.sex);
        }
        return false;
    }
    @Override
    public int hashCode() {//guava 重写hashCode
       return Objects.hashCode(name,age,sex);
    }
    /*@Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Person person = (Person) o;

        if (id != null ? !id.equals(person.id) : person.id != null) return false;
        if (name != null ? !name.equals(person.name) : person.name != null) return false;
        if (age != null ? !age.equals(person.age) : person.age != null) return false;
        return sex != null ? sex.equals(person.sex) : person.sex == null;
    }

    @Override
    public int hashCode() {
        int result = id != null ? id.hashCode() : 0;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + (age != null ? age.hashCode() : 0);
        result = 31 * result + (sex != null ? sex.hashCode() : 0);
        return result;
    }*/
}
